package com.nuoniu.sibanyun.service.production.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.entity.erp.ErpNumberSet;
import com.nuoniu.sibanyun.entity.production.*;
import com.nuoniu.sibanyun.mapper.erp.ErpNumberSetMapper;
import com.nuoniu.sibanyun.mapper.production.ErpWorkProcedureCardMainMapper;
import com.nuoniu.sibanyun.service.crm.ICrmGoodsService;
import com.nuoniu.sibanyun.service.erp.IErpAccountService;
import com.nuoniu.sibanyun.service.erp.IErpNumberSetService;
import com.nuoniu.sibanyun.service.production.IErpWorkProcedureCardDetailService;
import com.nuoniu.sibanyun.service.production.IErpWorkProcedureCardMainService;
import com.nuoniu.sibanyun.service.utils.ErpUtils;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 工序汇报——主表 服务实现类
 * </p>
 *
 * @author 白强
 * @since 2022-01-24
 */
@Service
public class ErpWorkProcedureCardMainServiceImpl extends ServiceImpl<ErpWorkProcedureCardMainMapper, ErpWorkProcedureCardMain> implements IErpWorkProcedureCardMainService {

    @Autowired
    private IErpWorkProcedureCardDetailService erpWorkProcedureCardDetailService;
    @Autowired
    private IErpAccountService accountService;
    @Autowired
    private ErpNumberSetMapper numberSetMapper;
    @Autowired
    private IErpNumberSetService numberSetService;
    @Autowired
    private ICrmGoodsService crmGoodsService;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveOrder(ErpWorkProcedureCardMain erpWorkProcedureCardMain) {
        List<ErpWorkProcedureCardDetail> orderDetailList = erpWorkProcedureCardMain.getOrderDetailList();
        if(null == orderDetailList) {
            throw new NuoNiuException("单据明细不能为空");
        }
        Long mainId = erpWorkProcedureCardMain.getId();
        UserInfo userInfo = UserThreadLocal.get();
        Integer currentAccountId = accountService.getCurrentAccountId();
        ErpWorkProcedureCardMain oldErpWorkProcedureCardMain = null;
        if(erpWorkProcedureCardMain.getId() == null) {
            erpWorkProcedureCardMain.setVoucherState(-1);
            erpWorkProcedureCardMain.setCompanyId(userInfo.getCompanyId());
            erpWorkProcedureCardMain.setAccountId(currentAccountId);
            erpWorkProcedureCardMain.setCreateUserId(userInfo.getUserId());
            erpWorkProcedureCardMain.setVoucherCode(getCode());
            erpWorkProcedureCardMain.setCreateUserName(userInfo.getRealName());
        }else{
            //校验详情（详情不能有其他单据的明细ID）
            boolean isHaveErrorId = orderDetailList.stream().anyMatch(f -> null != f.getOrderId() && !mainId.toString().equals(f.getOrderId().toString()));
            if(isHaveErrorId) {
                throw new NuoNiuException("单据明细错误：不能修改其他单据的明细记录");
            }
            oldErpWorkProcedureCardMain = getById(mainId);
            /**************  修改权限 *******************/
            if(!crmGoodsService.isHaveOperationRight(oldErpWorkProcedureCardMain.getCreateUserId().longValue())){
                throw new NuoNiuException("你没有权限操作该记录");
            }
            Integer voucherState = oldErpWorkProcedureCardMain.getVoucherState();
            if(null != voucherState && voucherState > 0){
                throw new NuoNiuException("已审核,不能修改");
            }
            erpWorkProcedureCardMain.setAccountId(oldErpWorkProcedureCardMain.getAccountId());
            erpWorkProcedureCardMain.setSourceVoucherCode(oldErpWorkProcedureCardMain.getSourceVoucherCode());
            erpWorkProcedureCardMain.setSourceVoucherId(oldErpWorkProcedureCardMain.getSourceVoucherId());
            erpWorkProcedureCardMain.setSourceVoucherType(oldErpWorkProcedureCardMain.getSourceVoucherType());
            erpWorkProcedureCardMain.setSourceVoucherDate(oldErpWorkProcedureCardMain.getSourceVoucherDate());
            //不可更新字段
            erpWorkProcedureCardMain.setVoucherCode(null);
        }
        Boolean result = this.saveOrUpdate(erpWorkProcedureCardMain);

        if(result){
            erpWorkProcedureCardDetailService.batchSaveDetails(erpWorkProcedureCardMain);
        }

    }

    @Override
    public String getCode() {
        UserInfo userInfo = UserThreadLocal.get();
        Integer currentAccountId = accountService.getCurrentAccountId();
        ErpNumberSet numberSet = numberSetMapper.getByCode("ProductionWorkReport", userInfo.getCompanyId(), currentAccountId);
        String dateStr = numberSet.getMedian() == 1 ? "%Y-%m-%d" : "%Y-%m";
        String code = baseMapper.getNewestCode(userInfo.getCompanyId(), dateStr);
        return numberSetService.getCode(numberSet, code);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void delete(Long id) {
        ErpWorkProcedureCardMain workProcedureCardMain = this.getById(id);
        if( null == workProcedureCardMain) {
            throw new NuoNiuException("记录不存在");
        }
        //校验状态
        Integer voucherState = workProcedureCardMain.getVoucherState();
        if(voucherState > 0) {
            throw new NuoNiuException("已提交，不能删除");
        }
        removeById(id);
        erpWorkProcedureCardDetailService.deleteByOrderId(id);
    }

    @Override
    public void submit(Long id, Integer status) {
        if(null == id || null == status || (null != status && (status > 0 || status < -1 ))) {
            throw new NuoNiuException("参数错误");
        }
        UserInfo userInfo = UserThreadLocal.get();
        ErpWorkProcedureCardMain workProcedureCardMain = this.getById(id);
        if( null == workProcedureCardMain) {
            throw new NuoNiuException("记录不存在");
        }
        //校验状态
        Integer voucherState = workProcedureCardMain.getVoucherState();
        /**  统一校验 提交状态 */
        ErpUtils.checkSubmitStatus(voucherState,status);
        //提交
        workProcedureCardMain.setVoucherState(status);
        workProcedureCardMain.setSubmitDate(LocalDateTime.now());
        workProcedureCardMain.setSubmitUserId(userInfo.getUserId());
        workProcedureCardMain.setSubmitUserName(userInfo.getRealName());
        this.updateById(workProcedureCardMain);
    }

    @Override
    public void examine(Long id, Integer status) {
        if(null == id || null == status ||  (status > 1 || status < 0) ) {
            throw new NuoNiuException("参数错误");
        }
        UserInfo userInfo = UserThreadLocal.get();
        ErpWorkProcedureCardMain workProcedureCardMain = this.getById(id);
        if (null == workProcedureCardMain) {
            throw new NuoNiuException("查询不到记录");
        }
        BigDecimal cumExecuteQuantity = workProcedureCardMain.getCumExecuteQuantity();
        Integer voucherState = workProcedureCardMain.getVoucherState();
        /** 统一校验 审核状态*/
        ErpUtils.checkExamineStatus(voucherState,status,cumExecuteQuantity);

        ErpWorkProcedureCardMain updateErpWorkProcedureCardMain = new ErpWorkProcedureCardMain();
        updateErpWorkProcedureCardMain.setVoucherState(status);
        updateErpWorkProcedureCardMain.setId(id);
        updateErpWorkProcedureCardMain.setReviewerDate(LocalDateTime.now());
        updateErpWorkProcedureCardMain.setReviewerUserId(userInfo.getUserId());
        updateErpWorkProcedureCardMain.setReviewerUserName(userInfo.getRealName());
        updateById(updateErpWorkProcedureCardMain);
    }
}
